<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="任务编号" prop="taskCode">
        <el-input
          v-model="queryParams.taskCode"
          placeholder="请输入任务编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="任务名称" prop="taskName">
        <el-input
          v-model="queryParams.taskName"
          placeholder="请输入任务名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="任务执行时间" label-width="120px">
        <el-date-picker
          v-model="daterangeExecTime"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="taskList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="序号" type="index" width="50"/>
      <el-table-column label="任务编号" align="center" prop="taskCode" width="180" show-overflow-tooltip/>
      <el-table-column label="任务名称" align="center" prop="taskName" width="130" show-overflow-tooltip/>
      <el-table-column label="算法编码" align="center" prop="algorithmCode" width="130" show-overflow-tooltip/>
      <el-table-column label="算法名称" align="center" prop="algorithmName" width="130" show-overflow-tooltip/>
      <el-table-column label="算法类型" align="center" prop="algorithmType" width="130" show-overflow-tooltip>
        <template slot-scope="scope">
          <dict-tag :options="dict.type.algorithm_type" :value="scope.row.algorithmType"/>
        </template>
      </el-table-column>
      <el-table-column label="任务执行时间" align="center" prop="execTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.execTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="任务执行人" align="center" prop="execBy"/>
      <el-table-column label="算法运行时长" align="center" prop="runTime">
        <template slot-scope="scope">
          {{ scope.row.runTime }} ms
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="taskStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.task_status" :value="scope.row.taskStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            v-if="scope.row.taskStatus === '0'"
            @click="handleUpdate(scope.row)"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            v-if="scope.row.taskStatus === '0'"
            @click="handleSubmit(scope.row)"
          >提交
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改内部检测任务对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="88px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="任务编号" prop="taskCode">
              <el-input v-model="form.taskCode" placeholder="系统自动生成" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务名称" prop="taskName">
              <el-input v-model="form.taskName" placeholder="请输入任务名称"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <!--          <el-col :span="12">-->
          <!--            <el-form-item label="设备名称" prop="eqpId">-->
          <!--              <el-select v-model="form.eqpId" placeholder="请选择设备" @change="handleEquipName" clearable-->
          <!--                         style="width: 100%"-->
          <!--              >-->
          <!--                <el-option-->
          <!--                  v-for="equip in equipList"-->
          <!--                  :key="equip.eqpId"-->
          <!--                  :label="equip.eqpName"-->
          <!--                  :value="equip.eqpId"-->
          <!--                ></el-option>-->
          <!--              </el-select>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <el-col :span="12">
            <el-form-item label="算法名称" prop="algorithmId">
              <el-select v-model="form.algorithmId" placeholder="请选择算法" style="width: 100%" @change="handleAlgorithm">
                <el-option
                  v-for="algorithm in algorithmList"
                  :key="algorithm.algorithmId"
                  :label="algorithm.algorithmName + ' -v' + algorithm.algorithmVersion"
                  :value="algorithm.algorithmId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="模型名称" prop="modelId">
              <el-select v-model="form.modelId" placeholder="请选择模型" style="width: 100%">
                <el-option
                  v-for="model in modelList"
                  :key="model.modelId"
                  :label="model.modelName + ' -v' + model.modelVersion"
                  :value="model.modelId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-table :data="paramList" height="300">
              <el-table-column label="序号" type="index" width="50"/>
              <el-table-column label="状态" type="index" width="50">
                <template slot-scope="scope">
                  <el-button v-if="scope.row.paramValue!== null && scope.row.paramValue.trim().length > 0"
                             type="success" size="mini" icon="el-icon-check" circle disabled
                  />
                  <el-button v-else type="info" icon="el-icon-close" size="mini" circle disabled/>
                </template>
              </el-table-column>
              <el-table-column label="参数编号" align="center" prop="paramCode" width="160" show-overflow-tooltip/>
              <el-table-column label="参数名称" align="center" prop="paramName" width="160" show-overflow-tooltip/>
              <el-table-column label="参数值" align="center" prop="paramValue">
                <template slot-scope="scope">
                  <div v-if="scope.row.paramType === '0'">
                    <el-input v-model="scope.row.paramValue" placeholder="请输入参数值"/>
                  </div>
                  <div v-else @click="handleRow(scope.row, scope.$index)">
                    <el-upload
                      :action="uploadFileUrl"
                      :before-upload="handleBeforeUpload"
                      :on-error="handleUploadError"
                      :on-exceed="handleExceed"
                      :on-success="handleUploadSuccess"
                      :show-file-list="false"
                      :headers="headers"
                      :limit="1"
                      :file-list="fileList" ref="fileUpload"
                    >
                      <el-tooltip class="item" effect="dark" :content="'上传结果：' + scope.row.fileName" placement="top">
                        <el-button size="small" type="primary">点击上传</el-button>
                      </el-tooltip>
                    </el-upload>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="显示顺序" align="center" prop="orderNum"/>
            </el-table>
          </el-col>
        </el-row>
        <el-form-item label-width="0">
          输出路径参考：/www/wwwroot/tyre/uploadPath/algorithm/yolov3/
        </el-form-item>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" maxlength="255" show-word-limit/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTask, getTask, delTask, addTask, updateTask, submitTask } from '@/api/algorithm/task'
import { listEquipData } from '@/api/equipment/equip'
import { listAlgorithmData } from '@/api/system/algorithm'
import { listConfigParams } from '@/api/algorithm/params'
import { getToken } from '@/utils/auth'
import { listModelData } from '@/api/algorithm/model'

export default {
  name: 'Task',
  dicts: ['task_status', 'module_type', 'algorithm_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 内部检测任务表格数据
      taskList: [],
      // 设备表格数据
      equipList: [],
      // Python算法表格数据
      algorithmList: [],
      // 质量模型管理表格数据
      modelList: [],
      // 参数列表
      paramList: [],
      uploadFileUrl: process.env.VUE_APP_BASE_API + '/common/upload', // 上传文件服务器地址
      headers: {
        Authorization: 'Bearer ' + getToken()
      },
      paramData: {},
      paramIndex: 0,
      fileList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 备注时间范围
      daterangeExecTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        taskCode: null,
        taskName: null,
        eqpId: null,
        eqpName: null,
        algorithmId: null,
        algorithmCode: null,
        algorithmName: null,
        moduleType: null,
        algorithmType: 'yolov3',
        execTime: null,
        execBy: null,
        execResult: null,
        runTime: null,
        taskStatus: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        taskName: [
          { required: true, message: '任务名称不能为空', trigger: 'blur' }
        ],
        eqpId: [
          { required: true, message: '设备不能为空', trigger: 'change' }
        ],
        algorithmId: [
          { required: true, message: '算法不能为空', trigger: 'change' }
        ],
        modelId: [
          { required: true, message: '模型不能为空', trigger: 'change' }
        ],
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询内部检测任务列表 */
    getList() {
      this.loading = true
      this.queryParams.params = {}
      if (null != this.daterangeExecTime && '' != this.daterangeExecTime) {
        this.queryParams.params['beginExecTime'] = this.daterangeExecTime[0]
        this.queryParams.params['endExecTime'] = this.daterangeExecTime[1]
      }
      listTask(this.queryParams).then(response => {
        this.taskList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    handleEquipName(val) {
      if (val) {
        this.equipList.forEach(item => {
          if (item.eqpId === val) {
            this.form.eqpName = item.eqpName
          }
        })
      }
    },
    handleAlgorithm(val) {
      if (val) {
        this.algorithmList.forEach(item => {
          if (item.algorithmId === val) {
            this.form.algorithmCode = item.algorithmCode
            this.form.algorithmName = item.algorithmName
            this.form.algorithmType = item.algorithmType
            this.form.moduleType = item.moduleType
          }
        })
        listConfigParams({ algorithmId: val, taskId: this.form.taskId }).then(res => {
          this.paramList = res.data
        })
      }
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        taskId: null,
        taskCode: null,
        taskName: null,
        eqpId: null,
        eqpName: null,
        algorithmId: null,
        algorithmCode: null,
        algorithmName: null,
        moduleType: null,
        algorithmType: 'yolov3',
        modelId: null,
        execTime: null,
        execBy: null,
        execResult: null,
        runTime: null,
        delFlag: null,
        taskStatus: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      }
      this.paramList = []
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeExecTime = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.taskId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    getEquipList() {
      listEquipData({ status: '0' }).then(response => {
        this.equipList = response.data
      })
    },
    getAlgorithmList() {
      listAlgorithmData({ algorithmType: 'yolov3', status: '0' }).then(res => {
        this.algorithmList = res.data
      })
    },
    getAlgorithmModel() {
      listModelData({ algorithmType: 'yolov3', status: '0' }).then(res => {
        this.modelList = res.data
      })
    },
    handleRow(row, index) {
      this.paramData = row
      this.paramIndex = index
    },
    handleBeforeUpload(file) {
      let fileType = ['zip']
      const fileName = file.name.split('.');
      const fileExt = fileName[fileName.length - 1];
      const isTypeOk = fileType.indexOf(fileExt) >= 0;
      if (!isTypeOk) {
        this.$modal.msgError(`文件格式不正确, 请上传${fileType.join("/")}格式文件!`);
        return false;
      }
      this.$modal.loading('正在上传文件，请稍候...')
      return true
    },
    // 文件个数超出
    handleExceed() {
      this.$modal.msgError(`上传文件数量不能超过 1 个!`)
    },
    // 上传失败
    handleUploadError(err) {
      this.$modal.msgError('上传文件失败，请重试')
      this.$modal.closeLoading()
    },
    handleUploadSuccess(res, file) {
      this.$modal.closeLoading()
      if (res.code === 200) {
        this.paramData.fileName = res.originalFilename
        this.paramData.relativePath = res.fileName
        this.paramData.absolutePath = res.absolutePath
        this.paramData.paramValue = res.absolutePath
        this.paramData.fileUrl = res.url
        this.paramData.fileSize = res.fileSize
        this.paramList.splice(this.paramIndex, 1, this.paramData)
      } else {
        this.$modal.msgError(res.msg)
        this.$refs.fileUpload.handleRemove(file)
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.getAlgorithmList()
      this.getAlgorithmModel()
      this.open = true
      this.title = '添加内部检测任务'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.getAlgorithmList()
      this.getAlgorithmModel()
      const taskId = row.taskId || this.ids
      getTask(taskId).then(response => {
        if (response.data.taskStatus === '0') {
          this.form = response.data
          this.paramList = response.data.paramsList
          this.open = true
          this.title = '修改内部检测任务'
        } else {
          this.$modal.msgWarning('已提交的数据不允许修改！')
        }
      })
    },
    handleSubmit(row) {
      this.$modal.confirm('是否确认提交内部检测任务编号为"' + row.taskCode + '"的数据项？').then(function() {
        return submitTask(row)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('提交成功')
      }).catch(() => {
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.form.paramsList = this.paramList
          if (this.form.taskId != null) {
            updateTask(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addTask(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const taskIds = row.taskId || this.ids
      this.$modal.confirm('是否确认删除内部检测任务编号为"' + taskIds + '"的数据项？').then(function() {
        return delTask(taskIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('algorithm/task/export', {
        ...this.queryParams
      }, `task_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
